# encoding=utf-8
import jieba
jieba.set_dictionary("./dict.txt")
jieba.initialize()
#
# seg_list = jieba.cut("武汉市江汉区发展大道180号移动公司", cut_all=True)
# print("Full Mode: " + "/ ".join(seg_list))  # 全模式
#
# seg_list = jieba.cut("武汉市江汉区发展大道180号移动公司", cut_all=False)
# print("Default Mode: " + "/ ".join(seg_list))  # 精确模式

seg_list = jieba.cut("武汉市江汉区发展大道180号移动公司")  # 默认是精确模式
print(", ".join(seg_list))
print('seg_list',seg_list)

# seg_list = jieba.cut_for_search("小明硕士毕业于中国科学院计算所，后在日本京都大学深造")  # 搜索引擎模式
# print(", ".join(seg_list))

#encoding:UTF-8
# python3.4 未读
# 依赖库
# xlrd
# xlwt
# requests

import urllib

import urllib.request
import xlrd
import xlwt
import requests
from html.parser import HTMLParser
import copy



from tkinter import *
import tkinter.messagebox
import threadpool

header = ['Gene Symbol','NCBI GeneID','GenBank Accession','NCBI Protein Accession','Species','Coding DNA Length','Gene Description',
                  'Primer Pair 1','Amplicon Size',"Sequence (5' -> 3')",'Length','Tm','Location',
                  'Primer Pair 2', 'Amplicon Size', "Sequence (5' -> 3')", 'Length', 'Tm', 'Location',
                  'Primer Pair 3', 'Amplicon Size', "Sequence (5' -> 3')", 'Length', 'Tm', 'Location']
stus = [header,]

def get_realtime_data(searchBox):
    global stus,header
    print('开始获取',searchBox)
    url = 'https://pga.mgh.harvard.edu/cgi-bin/primerbank/new_search2.cgi'
    user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
    values = {'selectBox': 'NCBI Gene Symbol', 'species': 'Human', 'searchBox':searchBox}
    headers = {'User-Agent': user_agent}
    data = urllib.parse.urlencode(values)
    r = requests.post(url, data=values)
    print(r.text)
    hp = MyHTMLParser(searchBox)
    hp.feed(r.text)
    hp.close()
    print('self.datadict', hp.datadict)
    print('self.tmpPrimer', hp.tmpPrimer)
    print('self.tmpSequence', hp.tmpSequence)
    print('listSequence', hp.listSequence)
    #存入data数据
    mydata = []
    opPri = {}
    for hang in ['F', 'R']:
        print(hang)
        tmpint = 0
        for lie in header:
            tmpint = tmpint + 1
            if tmpint <= 7:
                if lie == 'Gene Symbol':
                    mydata.append(hp.datadict[lie] + '-' + hang)
                else:
                    mydata.append(hp.datadict[lie])
            if tmpint >= 8 and tmpint <= 13:
                opPri = hp.listSequence['Primer Pair 1' + hang]
                mydata.append(opPri[lie])
            if tmpint >= 14 and tmpint <= 19:
                opPri = hp.listSequence['Primer Pair 2' + hang]
                mydata.append(opPri[lie])
            if tmpint >= 20 and tmpint <= 25:
                opPri = hp.listSequence['Primer Pair 3' + hang]
                mydata.append(opPri[lie])
        stus.append(mydata)
        print('mydata', mydata)
        mydata = []
    return r.text

        # v_http_resp = requests.get(v_url)
        # v_result = None
        # if v_http_resp.status_code == requests.codes.ok:
        #     v_result = v_http_resp.text
        # return v_result

class MyHTMLParser(HTMLParser):
    def __init__(self,genesymbol):
        HTMLParser.__init__(self)
        self.tmpCount = 0
        self.links = []
        self.genesymbol = genesymbol
        self.datadict = {'Gene Symbol':self.genesymbol,'NCBI GeneID':'','GenBank Accession':'','NCBI Protein Accession':'',
                         'Species':'','Coding DNA Length':'','Gene Description':'',
                        'Primer':[]}
        print('self.datadict.keys():',self.datadict.keys())
        self.tmpkey = ''
        self.tmplist = self.datadict.keys()
        self.tmpPrimer = {'id':1,'PrimerBank ID':'','Amplicon Size':'', 'Sequence':[]}
        self.iniSequence = {'type':'Forward Primer',"Sequence (5' -> 3')":'','Length':'','Tm':'','Location':''}
        self.tmpSequence = {'type':'Forward Primer',"Sequence (5' -> 3')":'','Length':'','Tm':'','Location':''}
        self.listSequence = {}
        self.stoptmp = 0



    def handle_starttag(self, tag, attrs):
        #print "Encountered the beginning of a %s tag" % tag
        if tag == "tr":
            if len(attrs) == 0:
                pass
            else:
                print("dict(attrs)",dict(attrs))
                for (variable, value) in attrs:
                    self.links.append(value)
                    if variable == "href":
                        self.links.append(value)

    def handle_data(self, data):
        if self.stoptmp == 1:
            pass
        if data.strip() != '':
            self.tmpCount = self.tmpCount + 1
            print(self.tmpCount,"Data:", data.strip())
            if self.tmpkey != '' and data.strip() not in self.tmplist and (self.tmpkey in self.tmplist or self.tmpkey in ['Sequence']):
                if 'Gene Description' in self.tmplist:
                    self.datadict[self.tmpkey]=data.strip()
                if 'Amplicon Size' in self.tmplist:
                    self.tmpPrimer[self.tmpkey]=data.strip()
                    print('self.tmpPrimer[self.tmpkey]',self.tmpPrimer[self.tmpkey])
                if 'Location' in self.tmplist:
                    if data.strip() in ['Forward Primer','Reverse Primer']:
                        self.tmpSequence['type']=data.strip()
                    if data.strip() not in ['Forward Primer','Reverse Primer','Sequence',"(5'",'-',"3')",'Location']:
                        if self.tmpCount in [80,32,37,56,61,85]:
                            self.tmpSequence["Sequence (5' -> 3')"]=data.strip()
                        if self.tmpCount in [81,33,38,57,62,86]:
                            self.tmpSequence['Length'] = data.strip()
                        if self.tmpCount in [82,34,39,58,63,87]:
                            self.tmpSequence['Tm'] = data.strip()
                        if self.tmpCount in [35,40,59,64,83,88]:
                            tmpid = 1
                            if self.tmpCount in [59,64]:
                                tmpid = 2
                            if self.tmpCount in [83,88]:
                                tmpid = 3

                            self.tmpSequence['Location'] = data.strip()
                            self.tmpSequence['Primer Pair '+str(tmpid)] = self.tmpPrimer['PrimerBank ID']
                            self.tmpSequence['Amplicon Size'] = self.tmpPrimer['Amplicon Size']
                            print('self.tmpSequence',self.tmpSequence)

                            self.listSequence['Primer Pair '+str(tmpid)+self.tmpSequence['type'][0:1]]=copy.deepcopy(self.tmpSequence)
                            self.tmpSequence = copy.deepcopy(self.iniSequence)
                            #Primer层再替换 123
                            if self.tmpCount in [40,64,88]:
                                self.tmplist = self.tmpPrimer.keys()


                if self.tmpkey == 'Gene Description' and self.datadict[self.tmpkey] != '':
                    #最外层解析完毕，进入里层
                    self.tmplist = self.tmpPrimer.keys()
                if self.tmpkey == 'Amplicon Size' : #and self.tmpPrimer[self.tmpkey] != ''
                    #Primer最外层解析完毕，进入里层
                    self.tmplist = ['Location']
                # if 'Location' == self.tmpkey  and self.tmpSequence[self.tmpkey] != '':
                #     self.stoptmp = 1
            if data.strip() in self.tmplist:
                self.tmpkey = data.strip()
            else:
                self.tmpkey == ''
            # print('self.datadict:',self.datadict)

from xlutils.copy import copy

class MainWindow:

    def buttonListener1(self, event):
        # shutil.copyfile('./地址.xlsx', './地址_new.xlsx')

        worksheet = xlrd.open_workbook('地址.xlsx')  # 打开excel文件
        self.new_excel = copy(worksheet)

        dbworksheet = xlrd.open_workbook('辅助资料.xlsx')  # 打开excel文件
        sheet_names = worksheet.sheet_names()  # 获取excel中所有工作表名
        sheet2 = worksheet.sheet_by_name('解析')  # 根据Sheet名获取数据
        sheet3 = dbworksheet.sheet_by_name('Page1')  # 根据Sheet名获取数据
        #写入部分

        #获取省市县信息
        nrows1 = sheet3.nrows  # 行数
        ncols1 = sheet3.ncols  # 列数
        num = 0
        for x in range(0, nrows1):
            value = sheet3.cell(x, 0).value
            if value == '省份':
                sno = sheet3.cell(x, 1).value
                sname = sheet3.cell(x, 2).value
                pl = (sno,sname)
                # print(pl)
                self.plist.append(pl)
                self.pnamelist.append(sname)
            if value == '城市':
                sno = sheet3.cell(x, 1).value
                sname = sheet3.cell(x, 2).value
                pl = (sno,sname)
                # print(pl)
                self.clist.append(pl)
                self.cnamelist.append(sname)
            if value == '区/县':
                sno = sheet3.cell(x, 1).value
                sname = sheet3.cell(x, 2).value
                pl = (sno,sname)
                # print(pl)
                self.qlist.append(pl)
                self.qnamelist.append(sname)

        nrows = sheet2.nrows  # 行数
        ncols = sheet2.ncols  # 列数
        num = 0
        for x in range(0, nrows):
            for y in range(0, ncols):
                value = sheet2.cell(x, y).value
                print(x,y,sheet2.cell(x, y).value)
                if value == 'Gene Symbol':
                    continue
                if value != '具体收件地址' and y == 8:
                    info_dict = {'add':value,'x':x,'y':y,'p':'','c':'','q':'','p_no':'','c_no':'','q_no':''}
                    seg_list = jieba.cut(value)  # 默认是精确模式

                    real_documents = list(jieba.cut(value, cut_all=False))
                    # seg_lists =
                    print(", ".join(seg_list))
                    print('real_documents',real_documents)
                    if len(real_documents)<3:
                        continue
                    print('real_documents',real_documents[0],real_documents[1],real_documents[2])
                    if x==-1:
                        info_dict['p']=real_documents[0]
                        info_dict['c']=real_documents[1]
                        info_dict['q']=real_documents[2]
                        print('info_dict',info_dict)
                    #有省市区正常解析
                    if real_documents[0] in self.pnamelist:
                        info_dict['p']=real_documents[0]
                        for x  in self.plist:
                            if x[1]==real_documents[0]:
                                info_dict['p_no'] = x[0]
                                print('info_dict[p_no][:2]',info_dict['p_no'][:2])
                        #查询城市
                        if info_dict['p_no'] != '':
                            if real_documents[1] in self.cnamelist:
                                info_dict['c'] = real_documents[1]
                                for x in self.clist:
                                    if x[0][:2]==info_dict['p_no'][:2] and x[1] == real_documents[1]:
                                        info_dict['c_no'] = x[0]
                                # 查询区县
                                if info_dict['c_no'] != '' and real_documents[2] in self.qnamelist:
                                    info_dict['q'] = real_documents[2]
                                    for x in self.qlist:
                                        if x[0][:4] == info_dict['c_no'][:4] and x[1] == real_documents[2]:
                                            info_dict['q_no'] = x[0]
                            elif real_documents[1] in self.qnamelist:
                                #获取县级市反查城市
                                c_tmp_no = '00'
                                print('获取县级市反查城市',real_documents)
                                info_dict['q'] = real_documents[1]
                                for x in self.qlist:
                                    if  x[1] == real_documents[1]:
                                        info_dict['q_no'] = x[0]
                                        c_tmp_no = x[0][:4]+c_tmp_no
                                #获取城市
                                for x in self.clist:
                                    if x[0] == c_tmp_no:
                                        info_dict['c_no'] = x[0]
                                        info_dict['c'] = x[1]


                    elif real_documents[0] in self.cnamelist:
                        # 首字不在省份内，在城市中，则反查省份
                        print('首字不在省份内，在城市中，则反查省份', real_documents)
                        p_no_tmp = '0000'
                        info_dict['c'] = real_documents[0]
                        for x in self.clist:
                            if x[1] == real_documents[0]:
                                info_dict['c_no'] = x[0]
                                p_no_tmp = x[0][:2]+p_no_tmp

                        print('首字不在省份内，在城市中，则反查省份p_no_tmp', p_no_tmp)
                        #反查省份
                        for x  in self.plist:
                            if x[0]==p_no_tmp:
                                info_dict['p_no'] = p_no_tmp
                                info_dict['p'] = x[1]
                                print('反查省份',info_dict )
                        #第二位则为区县
                        if info_dict['c_no'] != '' and real_documents[1] in self.qnamelist:
                            info_dict['q'] = real_documents[1]
                            for x in self.qlist:
                                if x[0][:4] == info_dict['c_no'][:4] and x[1] == real_documents[1]:
                                    info_dict['q_no'] = x[0]


                        # info_dict['c']=real_documents[1]
                        # info_dict['q']=real_documents[2]
                    if info_dict['p_no'] != '':
                        num = num + 1
                        print(num,'info_dict',info_dict)
                    else:
                        print(num,'qk_info_dict',info_dict)



                    self.bhlist.append(info_dict)

                    # print('解析', sheet2.cell(x, y).value)

        tkinter.messagebox.showinfo("成功提醒", "导入"+str(num)+"条完成，请点导出，生成《导出.xls》")

    def buttonListener2(self, event):
        print('开始解析')
        self.tmpGeneSymbol = 'SLC5A5'
        '''
        url = 'https://pga.mgh.harvard.edu/cgi-bin/primerbank/new_search2.cgi'

        user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'

        values = {'selectBox': 'NCBI Gene Symbol','species':'Human','searchBox':'SLC5A5'}

        headers = {'User-Agent': user_agent}

        data = urllib.parse.urlencode(values)

        r = requests.post(url, data=values)

        print(r.text)
        '''

        # v_index_array = ['SLC5A5', 'EGR1']
        # v_index_array = self.bhlist
        # v_thread_pool = threadpool.ThreadPool(len(v_index_array))
        # requests = threadpool.makeRequests(get_realtime_data, v_index_array)
        # [v_thread_pool.putRequest(req) for req in requests]
        # v_thread_pool.wait()

        # global stus, header
        # print('stus',stus)
        sheet_index = self.new_excel.sheet_index("解析")
        ws = self.new_excel.get_sheet(sheet_index)
        for i in self.bhlist:
            if i['p'] != '':
                ws.write(i['x'], 0, i['p'])
            if i['p_no'] != '':
                ws.write(i['x'], 1, i['p_no'])
            if i['q'] != '':
                ws.write(i['x'], 3, i['q'])
            if i['q_no'] != '':
                ws.write(i['x'], 4, i['q_no'])
            if i['c'] != '':
                ws.write(i['x'], 6, i['c'])
            if i['c_no'] != '':
                ws.write(i['x'], 7, i['c_no'])

        self.new_excel.save('导出.xls')  # 保存到当前目录下
        tkinter.messagebox.showinfo("成功提醒", "完成导出《导出.xls》")

    def buttonListener3(self, event):
        tkinter.messagebox.showinfo("messagebox", "this is button 3 dialog")

    def buttonListener4(self, event):
        tkinter.messagebox.showinfo("messagebox", "this is button 4 dialog")

    def __init__(self):
        self.new_excel = None
        self.bhlist = []
        self.plist = []
        self.clist = []
        self.qlist = []
        self.pnamelist = []
        self.cnamelist = []
        self.qnamelist = []
        self.tmpGeneSymbol=''
        self.frame = Tk()
        import datetime
        end_date = datetime.datetime.strptime("2099-10-1", "%Y-%m-%d")
        self.frame.title(u'省市县数据分析')
        datetimenowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 现在
        begin_date = datetime.datetime.strptime(datetimenowTime, "%Y-%m-%d %H:%M:%S")
        print(end_date)
        print(datetimenowTime)
        print(begin_date)
        if begin_date < end_date:
            self.button1 = Button(self.frame, text="导入", width=5, height=1)
            self.button2 = Button(self.frame, text="导出", width=5, height=1)

            self.button1.grid(row=0, column=0, padx=5, pady=5)
            self.button2.grid(row=0, column=1, padx=5, pady=5)

            import datetime
            # 以当前时间作为起始点，days=-7向前偏移7天，days=7向后偏移7天
            time_now = datetime.datetime.now()
            time = (time_now + datetime.timedelta(days=7)).strftime("%Y%m%d")
            print(time)

            self.button1.bind("<ButtonRelease-1>", self.buttonListener1)
            self.button2.bind("<ButtonRelease-1>", self.buttonListener2)

            self.L1 = Label(self.frame,
                            text='Q微同号494514014，淘宝店铺guoff.taobao.com;待解析文件名:地址.xlsx,先导入，提示成功后；再点解析即可，格式及sheet名保持一致。 ',
                            height=5,
                            justify='left',
                            wraplength=280,
                            anchor='e'
                            )
            self.L1.grid(row=1, column=0, columnspan=2)
        else:
            self.L1 = Label(self.frame,
                            text='Q微同号494514014，淘宝店铺guoff.taobao.com;已过试用期，请联系管理员。 ',
                            height=5,
                            justify='left',
                            wraplength=280,
                            anchor='e'
                            )
            self.L1.grid(row=1, column=0, columnspan=2)




        sw = self.frame.winfo_screenwidth()
        sh = self.frame.winfo_screenheight()

        # 得到屏幕高度

        ww = 302

        wh = 136

        # 窗口宽高为100

        x = (sw - ww) / 2

        y = (sh - wh) / 2

        self.frame.geometry("%dx%d+%d+%d" % (ww, wh, x, y))

        sh = self.frame.winfo_screenheight()
        self.frame.mainloop()



window = MainWindow()

